#!/usr/bin/env python
# Create: 2019/5/29
__author__ = '749B'
"""每一个告警策略返回一个最新触发的告警的ID"""

import requests

from sds.swis_login import swis

CSV_KEYS = ('OID', 'Name', 'Severity', 'AlertID', 'Description', 'Frequency', 'LastEdit', 'ObjectType')

SQL_STR = "SELECT MAX(o.AlertObjectID) AS OID, " \
          "a.Name, a.Severity, a.AlertID, a.Description, a.Frequency, a.LastEdit, a.ObjectType " \
          "FROM Orion.AlertObjects o " \
          "JOIN Orion.AlertConfigurations a ON o.AlertID = a.AlertID " \
          "GROUP BY o.AlertID"


def run():
    results = swis.query(SQL_STR)
    if not results:
        return
    res = results.pop('results')
    if results:
        return
    if len(res) < 1:
        return
    return res


def to_csf(data):
    res_f = open('alert_objects.csv', 'w', encoding='utf-8')
    line = ','.join([i for i in data[0]])
    res_f.writelines((line, '\n'))
    for item in data:
        line = ','.join([str(v).replace('\r\n', '').replace(',', '_') for _, v in item.items()])
        res_f.writelines((line, '\n'))


requests.packages.urllib3.disable_warnings()


if __name__ == '__main__':
    res = run()
    if not res:
        exit("查询出错")
    # print(res)
    to_csf(res)


